package com.haierp.service.yitaoItem.impl;


import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.haierp.enums.ItemStatus;
import com.haierp.enums.PlatformType;
import com.haierp.exception.ErpCommonException;
import com.haierp.mapper.OuterItemMapper;
import com.haierp.mapper.OuterItemSkuMapper;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.item.OuterItem;
import com.haierp.model.item.OuterItemSku;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IUploadFileService;
import com.haierp.service.yitao.YiTaoProductService;
import com.haierp.service.yitaoItem.YTIOuterItemService;
import com.haierp.util.yitao.YtProductDataUtils;
import com.haierp.vo.ItemQueryVO;
import com.wangzhixuan.commons.utils.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;

@Service
public class YTOuterItemServiceImpl extends SuperServiceImpl<OuterItemMapper, OuterItem> implements YTIOuterItemService {

    @Autowired
    private IItemService itemService;
    @Autowired
    private IUploadFileService uploadFileService;
    @Autowired
    private YiTaoProductService yiTaoProductService;
    @Autowired
    private OuterItemSkuMapper outerItemSkuMapper;
    @Autowired
    private IInventoryService inventoryService;

    @Override
    public void synItemYitao(Long itemId) {
        ItemQueryVO itemQueryVO = new ItemQueryVO();
        itemQueryVO.setItemId(itemId);
        Item item = itemService.queryItem(itemQueryVO);
        if (item.getYzisSale() == 0) {
            return;
        }
        if (item.getCompanyId() != 1) {
            throw new ErpCommonException("商品代码：" + item.getItemCode() + "商品不能执行此操作！");
        }
        if (item.getStatus() == ItemStatus.INIT.getCode()) { //未同步过
            //构造上传的商品对象
            JSONObject map = YtProductDataUtils.ProductInfoConvert(item);
            JSONObject result = yiTaoProductService.yitaoItemCreate(map);
            String status = result.getString("status");
            if (status.equals("0")) {
                JSONObject data = result.getJSONObject("data");
                item.setImageIds("1");//测试使用
                addOuterItemYt(item, data);
            } else {
                throw new ErpCommonException("商品代码：" + item.getItemCode() + "商品同步失败!");
            }

        } else {//已同步过
            if (item.getStatus() != ItemStatus.LISTING.getCode()) {
                throw new ErpCommonException("商品代码：" + item.getItemCode() + "下架商品不能同步");
            }
            //构造上传的商品对象
            OuterItem outerItemQuery = new OuterItem();
            outerItemQuery.setItemId(itemId);
            outerItemQuery.setPlatformType(PlatformType.YITAO.getCode());
            OuterItem outerItem = this.baseMapper.selectOne(outerItemQuery);
            if (outerItem != null) {
                //构造上传的商品对象
                JSONObject map = YtProductDataUtils.ProductInfoConvert(item);
                JSONObject result = yiTaoProductService.yitaoItemCreate(map);
                String status = result.getString("status");
                if (status.equals("0")) {
                    JSONObject data = result.getJSONObject("data");

                    /*item.setImageIds(youzanItemUpdateParams.getImageIds());*/
                    updateOuterItemYt(item, data);
                } else {
                    throw new ErpCommonException("一桃商品{}同步失败", String.valueOf(outerItem.getId()));
                }


            } else {
                throw new ErpCommonException("一桃商品有误");
            }
        }
    }


    /**
     * 新增yitao外部商品和SKU信息
     *
     * @param item
     * @param
     */
    private void addOuterItemYt(Item item, JSONObject data) {

        //String alias = item.getItemShort();//有赞别名
        String alias = item.getItemCode() + "_" + PlatformType.YITAO.getCode();
        Long numIid = data.getLong("id");//有赞ID
        //1、保存外部商品
        OuterItem outerItem = new OuterItem();
        outerItem.setItemId(item.getId());
        outerItem.setPlatformType(PlatformType.YITAO.getCode());
        OuterItem selOuterItem = this.baseMapper.selectOne(outerItem);
        outerItem.setOuterAlias(alias);
        outerItem.setOuterId(numIid);
        outerItem.setStatus(ItemStatus.LISTING.getCode());//上架
        outerItem.setImageIds(item.getImageIds());
        try {
            if (selOuterItem == null) {
                this.baseMapper.insert(outerItem);
            } else {
                outerItem.setId(selOuterItem.getId());
                this.baseMapper.updateSelectiveById(outerItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<ItemSku> itemSkuList = item.getItemSkus();
        Map<String, Long> itemSkuIdMap = new HashMap<String, Long>();
        for (ItemSku itemSku : itemSkuList) {
            itemSkuIdMap.put(itemSku.getSkuCode(), itemSku.getId());
        }

        //2、更新外部SKU信息
        /*ItemSkuOpenModel[]goodsSku =   youzanItemCreateResult.getItem().getSkus();*/
        JSONArray goodsSku = data.getJSONArray("productSkuList");
        if (goodsSku != null && goodsSku.size() > 0) {
            for (int i = 0; i < goodsSku.size(); i++) {
                JSONObject sku = goodsSku.getJSONObject(i);
                OuterItemSku outerItemSku = new OuterItemSku();
                outerItemSku.setSkuId(itemSkuIdMap.get(sku.getString("sourceSkuCode")));//sku编码
                outerItemSku.setPlatformType(PlatformType.YITAO.getCode());
                OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(outerItemSku);
                outerItemSku.setItemId(item.getId());
                outerItemSku.setOuterId(numIid);
                outerItemSku.setOuterSkuId(sku.getLong("id"));
                outerItemSku.setOuterItemId(outerItem.getId());
                outerItemSku.setSkuCode(sku.getString("sourceSkuCode"));
                outerItemSku.setOuterSkuCode(sku.getString("productSkuCode"));
                if (selOuterItemSku == null) {
                    outerItemSkuMapper.insert(outerItemSku);
                } else {
                    outerItemSku.setId(selOuterItemSku.getId());
                    outerItemSkuMapper.updateSelectiveById(outerItemSku);
                }
            }
        }

        //3、更新erp商品信息
        item.setStatus(ItemStatus.LISTING.getCode());
        item.setGmtModify(new Date());
        itemService.updateById(item);

    }

    /**
     * 批量上架
     *
     * @param item
     */
    @Override
    public void listingYitao(Item item) {
        //是否可在有赞销售1可以0不可以
        if (item.getYzisSale() == 0) {
            return;
        }
        //查询出第三方平台帐号，上架
        OuterItem outerItemQuery = new OuterItem();
        outerItemQuery.setItemId(item.getId());
        OuterItem outerItemDb = this.baseMapper.selectOne(outerItemQuery);
        if (outerItemDb == null) {
            throw new ErpCommonException("更新outerItem 订单信息错误;");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", item.getId());
        //map.put("isSale", true);
        map.put("isSale", false);
        String result = yiTaoProductService.yitaoItemUpdateListing(map);
        if (StringUtils.isNotBlank(result)){
            JSONObject resultObject = JSONObject.fromObject(result);
            String status = resultObject.getString("status");
            if (status.equals("0")) {
                //更新商品状态
                item.setStatus(ItemStatus.LISTING.getCode());
                item.setGmtModify(new Date());
                itemService.updateById(item);
                //更新外部商品状态
                outerItemDb.setStatus(ItemStatus.LISTING.getCode());
                this.baseMapper.updateById(outerItemDb);
            }else{
                throw new ErpCommonException("一桃商品{}上架失败", String.valueOf(item.getId()));
            }
        }else{
            throw new ErpCommonException("一桃商品{}上架失败", String.valueOf(item.getId()));
        }


    }

    /**
     * 批量下架接口
     *
     * @param item
     */
    @Override
    public void delistingYitao(Item item) {
        OuterItem outerItemQuery = new OuterItem();
        outerItemQuery.setItemId(item.getId());
        OuterItem outerItemDb = this.baseMapper.selectOne(outerItemQuery);
        if (outerItemDb == null) {
            throw new ErpCommonException("更新outerItem 订单信息错误;");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", item.getId());
        map.put("isSale", false);
       String result = yiTaoProductService.yitaoItemUpdateListing(map);
        JSONObject resultObject = JSONObject.fromObject(result);
        String status = resultObject.getString("status");
        if (StringUtils.isNotBlank(result)){
            if (!status.equals("0")) {
                throw new ErpCommonException("一桃商品{}下架失败", String.valueOf(item.getId()));
            }
            //更新商品状态
            item.setStatus(ItemStatus.DELISTING.getCode());
            item.setGmtModify(new Date());
            itemService.updateById(item);
            //更新外部商品状态
            outerItemDb.setStatus(ItemStatus.DELISTING.getCode());
            this.baseMapper.updateById(outerItemDb);
        }else {
            throw new ErpCommonException("一桃商品{}下架失败", String.valueOf(item.getId()));
        }
    }


    private void updateOuterItemYt(Item item, JSONObject data) {
        Long numIid = data.getLong("outId");//有赞ID
        //1、保存外部商品
        OuterItem outerItem = new OuterItem();
        outerItem.setItemId(item.getId());
        outerItem.setPlatformType(PlatformType.YITAO.getCode());
        OuterItem outerItemDb = this.baseMapper.selectOne(outerItem);
        if (outerItemDb == null) {
            throw new ErpCommonException("更新outerItem 订单信息错误");
        } else {
            outerItemDb.setImageIds(item.getImageIds());
            this.baseMapper.updateSelectiveById(outerItemDb);
        }
        List<ItemSku> itemSkuList = item.getItemSkus();
        Map<String, Long> itemSkuIdMap = new HashMap<String, Long>();
        for (ItemSku itemSku : itemSkuList) {
            itemSkuIdMap.put(itemSku.getSkuCode(), itemSku.getId());
        }

        //2、更新外部SKU信息
		/*YouzanItemGetParams youzanItemGetParams = new YouzanItemGetParams();
		youzanItemGetParams.setItemId(outerItemDb.getOuterId());
		youzanItemGetParams.setAlias(outerItemDb.getOuterAlias());
		YouzanItemGetResult itemGetResult = yzService.youzanItemGet(youzanItemGetParams);//获取单个商品信息*/
        /*YouzanItemGetResult.ItemSkuOpenModel[] goodsSku = itemGetResult.getItem().getSkus();*/
        JSONArray jsonArray = data.getJSONArray("productSkuList");//获取sku信息
        if (jsonArray != null && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (StringUtil.isBlank(jsonObject.getString("sourceSkuCode")) || itemSkuIdMap.get(jsonObject.getString("sourceSkuCode")) == null) {
                    continue;
                }
                OuterItemSku outerItemSku = new OuterItemSku();
                outerItemSku.setSkuId(itemSkuIdMap.get(jsonObject.getString("sourceSkuCode")));
                outerItemSku.setPlatformType(PlatformType.YITAO.getCode());
                OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(outerItemSku);
                outerItemSku.setItemId(item.getId());
                outerItemSku.setOuterId(numIid);
                outerItemSku.setOuterSkuId(jsonObject.getLong("id"));
                outerItemSku.setOuterItemId(outerItemDb.getId());
                outerItemSku.setSkuCode(jsonObject.getString("productSkuCode"));
                if (selOuterItemSku == null) {
                    outerItemSkuMapper.insert(outerItemSku);
                } else {
                    outerItemSku.setId(selOuterItemSku.getId());
                    outerItemSkuMapper.updateSelectiveById(outerItemSku);
                }
            }
        }

    }

    /**
     * 一桃同步库存
     *
     * @param itemId
     * @param skuId
     */
    @Override
    public void synSkuInventoryYitao(Long itemId, Long skuId) {
        //查询是否同步到有赞，并且为已上架状态
        OuterItem outerItemQuery = new OuterItem();
        outerItemQuery.setItemId(itemId);
        OuterItem outerItemDb = this.baseMapper.selectOne(outerItemQuery);
        if (outerItemDb == null) {
//			throw new ErpCommonException("更新outerItem 订单信息错误;");
            this.logger.info("没有找到对应的有赞商品，itemId:" + itemId);
        } else {
            //上架中的商品
            if (outerItemDb.getStatus() != null && outerItemDb.getStatus() == ItemStatus.LISTING.getCode()) {
                OuterItemSku outerItemSkuQuery = new OuterItemSku();
                outerItemSkuQuery.setItemId(itemId);
                outerItemSkuQuery.setSkuId(skuId);
                OuterItemSku outerItemSkuDb = outerItemSkuMapper.selectOne(outerItemSkuQuery);
                if (outerItemSkuDb != null && outerItemSkuDb.getOuterSkuId() != null) {
                    Inventory inventory = inventoryService.queryInventoryBySkuId(itemId, skuId);//获取库存信息
                    //同步
                    if (inventory != null) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("productId", itemId);
                        map.put("skuId", skuId);
                        map.put("entityStock", inventory.getInventory());//实际库存
                        yiTaoProductService.yitaoItemSkuUpdate(map);
                    } else {
                        this.logger.info("没有找到库存信息，skuId:" + skuId);
                    }
                } else {
                    this.logger.info("没有找到对应的有赞sku，skuId:" + skuId);
                }
            } else {
                this.logger.info("商品未上架不能同步库存，skuId:" + skuId);
            }
        }

    }


/*
	private YouzanItemCreateParams createYouzanAddItem(Item item) {
		YouzanItemCreateParams youzanItemCreateParams = new YouzanItemCreateParams();
		youzanItemCreateParams.setTitle(item.getName());
		if(StringUtils.isNotEmpty(item.getDetail())){
			try {
				//String decodeStr = URLDecoder.decode(item.getDetail(),"UTF-8"); 
				youzanItemCreateParams.setDesc(item.getDetail());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			youzanItemCreateParams.setDesc(item.getName());
		}
		if(item.getFreight()!=null && item.getFreight()>0) {
			youzanItemCreateParams.setPostFee((long)(item.getFreight()*100));
		} else {
			youzanItemCreateParams.setPostFee(0L);
		}
		//图片
		String itemPic = item.getMainPic();
		ItemImages itemImages = initImages( itemPic);
		if(itemImages != null) {
			ByteWrapper[] byteWrapperArr = itemImages.getByteWrappers();
			String imageIds = null;
			for(int i=0; i<byteWrapperArr.length; i++) {
				ByteWrapper[] pByteWrapperArr = new ByteWrapper[1];
				pByteWrapperArr[0] = byteWrapperArr[i];
				YouzanMaterialsStoragePlatformImgUploadParams youzanMaterialsStoragePlatformImgUploadParams = new YouzanMaterialsStoragePlatformImgUploadParams();
				youzanMaterialsStoragePlatformImgUploadParams.setImage(pByteWrapperArr);
				YouzanMaterialsStoragePlatformImgUploadResult result = yzService.youzanMaterialsStoragePlatformImgUpload(youzanMaterialsStoragePlatformImgUploadParams);
				if(imageIds == null) {
					imageIds = result.getImageId().toString();
				} else {
					imageIds += "," + result.getImageId().toString();
				}
			}
			youzanItemCreateParams.setImageIds(imageIds);
		}
		
		youzanItemCreateParams.setItemNo(item.getItemCode());
		//SKU
		 List<ItemSku> itemSkus = item.getItemSkus();
		//List<YouZanSku> youZanSkuList = initSkuJson(itemSkus);
		 List<Map<String,Object>> youZanSkuList = initSkuJsonOne(itemSkus);
		 if(CollectionUtils.isNotEmpty(youZanSkuList)){
			 String skusWithJson = HaiJsonUtils.toJson(youZanSkuList);
			 youzanItemCreateParams.setSkuStocks(skusWithJson);
		 }         
		 Double minSalePrice = itemSkus.get(0).getSalePrice();
		 for (ItemSku itemSku : itemSkus) {
			 if(itemSku.getSalePrice()<minSalePrice){
				 minSalePrice = itemSku.getSalePrice();
			 }
		}
		 youzanItemCreateParams.setPrice((long)(minSalePrice*100));
		return youzanItemCreateParams;
	}

	private YouzanItemUpdateParams createYouzanUpdateItem(Item item) {
		YouzanItemUpdateParams youzanItemUpdateParams = new YouzanItemUpdateParams();
		youzanItemUpdateParams.setTitle(item.getName());
		if(StringUtils.isNotEmpty(item.getDetail())){
			try {
				//String decodeStr = URLDecoder.decode(item.getDetail(),"UTF-8"); 
				youzanItemUpdateParams.setDesc(item.getDetail());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if(item.getFreight()!=null && item.getFreight()>0) {
			youzanItemUpdateParams.setPostFee((long)(item.getFreight()*100));
		} else {
			youzanItemUpdateParams.setPostFee(0L);
		}
		//图片
		String itemPic = item.getMainPic();
		ItemImages itemImages = initImages( itemPic);
		if(itemImages != null) {
			ByteWrapper[] byteWrapperArr = itemImages.getByteWrappers();
			String imageIds = null;
			for(int i=0; i<byteWrapperArr.length; i++) {
				ByteWrapper[] pByteWrapperArr = new ByteWrapper[1];
				pByteWrapperArr[0] = byteWrapperArr[i];
				YouzanMaterialsStoragePlatformImgUploadParams youzanMaterialsStoragePlatformImgUploadParams = new YouzanMaterialsStoragePlatformImgUploadParams();
				youzanMaterialsStoragePlatformImgUploadParams.setImage(pByteWrapperArr);
				YouzanMaterialsStoragePlatformImgUploadResult result = yzService.youzanMaterialsStoragePlatformImgUpload(youzanMaterialsStoragePlatformImgUploadParams);
				if(imageIds == null) {
					imageIds = result.getImageId().toString();
				} else {
					imageIds += "," + result.getImageId().toString();
				}
			}
			youzanItemUpdateParams.setImageIds(imageIds);
		}
		//SKU
		 List<ItemSku> itemSkus = item.getItemSkus();
		//List<YouZanSku> youZanSkuList = initSkuJson(itemSkus);
		 List<Map<String,Object>> youZanSkuList = initSkuJsonOne(itemSkus);
		 if(CollectionUtils.isNotEmpty(youZanSkuList)){
			 String skusWithJson = HaiJsonUtils.toJson(youZanSkuList);
			 youzanItemUpdateParams.setSkuStocks(skusWithJson);
		 }
		 Double minSalePrice = itemSkus.get(0).getSalePrice();
		 for (ItemSku itemSku : itemSkus) {
			 if(itemSku.getSalePrice() < minSalePrice){
				 minSalePrice = itemSku.getSalePrice();
			 }
		}
		 youzanItemUpdateParams.setPrice((long)(minSalePrice*100));
		return youzanItemUpdateParams;
	}

//	private List<YouZanSku> initSkuJson(List<ItemSku> itemSkus) {
//		List<YouZanSku> youZanSkuList = Lists.newArrayList();
//		if(CollectionUtils.isNotEmpty(itemSkus)){
//			for(ItemSku itemSku:itemSkus){
//				YouZanSku yzs = new  YouZanSku();
//				yzs.setItemNo(itemSku.getSkuCode());//重点：这里的sku_item_no对应的有赞 outer_id
//				yzs.setPrice(itemSku.getSalePrice());
//				int skuQuantity = 0;
//				int lockedVirtualInv = itemSku.getLockedVirtualInv();
//				if(itemSku.getVirtualInv()>0){
//					skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
//				}else{
//					skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
//				}
//				if(skuQuantity<0) skuQuantity = 0;
//				yzs.setQuantity(skuQuantity);
//				
//				if(StringUtil.isNotBlank(itemSku.getColor())) {
//					yzs.getSkus().setColor(itemSku.getColor());
//				}
//				if(StringUtil.isNotBlank(itemSku.getScale())) {
//					yzs.getSkus().setScale(itemSku.getScale());
//				}
//				youZanSkuList.add(yzs);
//			}
//		}else{ 
//			throw new ErpCommonException("没有SKU");
//		}
//		return youZanSkuList;
//	}

	private List<Map<String,Object>> initSkuJsonOne(List<ItemSku> itemSkus) {
		List<Map<String,Object>> youZanSkuList = Lists.newArrayList();
		Map<String, ItemSku> itemSkuMap = Maps.newHashMap();
		Set<String> colorSet = Sets.newHashSet();
		Set<String> scaleSet = Sets.newHashSet();
		if(CollectionUtils.isNotEmpty(itemSkus)){
			for(ItemSku itemSku:itemSkus) {
				String colorScaleKey = "";
				if(StringUtil.isNotBlank(itemSku.getColor())) {
					colorSet.add(itemSku.getColor());
					colorScaleKey += itemSku.getColor();
				}
				if(StringUtil.isNotBlank(itemSku.getScale())) {
					scaleSet.add(itemSku.getScale());
					colorScaleKey += itemSku.getScale();
				}
				itemSkuMap.put(colorScaleKey, itemSku);
			}
			if(colorSet.size()>0 && scaleSet.size()==0) {
				for(String color : colorSet) {
					Map<String,Object> skuStocksMap = new HashMap<String,Object>();
					ItemSku itemSku = itemSkuMap.get(color);
					skuStocksMap.put("price", itemSku.getSalePrice()*100);				
					int skuQuantity = 0;
					int lockedVirtualInv = itemSku.getLockedVirtualInv();
					if(itemSku.getVirtualInv()>0){
						skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
					}else{
						skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
					}
					if(skuQuantity<0) skuQuantity = 0;
					skuStocksMap.put("quantity", skuQuantity);
					skuStocksMap.put("item_no", itemSku.getSkuCode()); //重点：这里的sku_item_no对应的有赞 outer_id
					List<Map<String, Object>> skusList = new ArrayList<>();
					Map<String, Object> skusColorMap = new HashMap<String, Object>();
					skusColorMap.put("v", itemSku.getColor());
					skusColorMap.put("k", "颜色");
					skusList.add(skusColorMap);
					
					skuStocksMap.put("skus", skusList);
					youZanSkuList.add(skuStocksMap);
				}
			} else if(scaleSet.size()>0 && colorSet.size()==0) {
				for(String scale : scaleSet) {
					Map<String,Object> skuStocksMap = new HashMap<String,Object>();
					ItemSku itemSku = itemSkuMap.get(scale);
					skuStocksMap.put("price", itemSku.getSalePrice()*100);				
					int skuQuantity = 0;
					int lockedVirtualInv = itemSku.getLockedVirtualInv();
					if(itemSku.getVirtualInv()>0){
						skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
					}else{
						skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
					}
					if(skuQuantity<0) skuQuantity = 0;
					skuStocksMap.put("quantity", skuQuantity);
					skuStocksMap.put("item_no", itemSku.getSkuCode()); //重点：这里的sku_item_no对应的有赞 outer_id
					List<Map<String, Object>> skusList = new ArrayList<>();
					Map<String, Object> skusScaleMap = new HashMap<String, Object>();
					skusScaleMap.put("v", itemSku.getScale());
					skusScaleMap.put("k", "尺寸");
					skusList.add(skusScaleMap);
					
					skuStocksMap.put("skus", skusList);
					youZanSkuList.add(skuStocksMap);
				}
			} else {
				for(String color : colorSet) {
					for(String scale : scaleSet) {
						Map<String,Object> skuStocksMap = new HashMap<String,Object>();
						ItemSku itemSku = itemSkuMap.get(color+scale);
						if(itemSku == null) {
							skuStocksMap.put("price", 100000*100);				
							skuStocksMap.put("quantity", 0);
							skuStocksMap.put("item_no", ""); //重点：这里的sku_item_no对应的有赞 outer_id
							List<Map<String, Object>> skusList = new ArrayList<>();
							Map<String, Object> skusColorMap = new HashMap<String, Object>();
							Map<String, Object> skusScaleMap = new HashMap<String, Object>();
							skusColorMap.put("v", color);
							skusColorMap.put("k", "颜色");
							skusList.add(skusColorMap);
							skusScaleMap.put("v", scale);
							skusScaleMap.put("k", "尺寸");
							skusList.add(skusScaleMap);
							
							skuStocksMap.put("skus", skusList);
							youZanSkuList.add(skuStocksMap);
						} else {
							skuStocksMap.put("price", itemSku.getSalePrice()*100);				
							int skuQuantity = 0;
							int lockedVirtualInv = itemSku.getLockedVirtualInv();
							if(itemSku.getVirtualInv()>0){
								skuQuantity = itemSku.getVirtualInv() - lockedVirtualInv;
							}else{
								skuQuantity = itemSku.getTotalAvailableInv() - lockedVirtualInv;
							}
							if(skuQuantity<0) skuQuantity = 0;
							skuStocksMap.put("quantity", skuQuantity);
							skuStocksMap.put("item_no", itemSku.getSkuCode()); //重点：这里的sku_item_no对应的有赞 outer_id
							List<Map<String, Object>> skusList = new ArrayList<>();
							Map<String, Object> skusColorMap = new HashMap<String, Object>();
							Map<String, Object> skusScaleMap = new HashMap<String, Object>();
							skusColorMap.put("v", itemSku.getColor());
							skusColorMap.put("k", "颜色");
							skusList.add(skusColorMap);
							skusScaleMap.put("v", itemSku.getScale());
							skusScaleMap.put("k", "尺寸");
							skusList.add(skusScaleMap);
							
							skuStocksMap.put("skus", skusList);
							youZanSkuList.add(skuStocksMap);
						}
					}
				}
			}
		}else{ 
			throw new ErpCommonException("没有SKU");
		}
		return youZanSkuList;
	}
	private ItemImages  initImages( String itemPic) {
		if(StringUtils.isNotEmpty(itemPic)){
			ItemImages itemImages = new ItemImages();
			PicModel pm = HaiJsonUtils.toBean(itemPic, PicModel.class);
			ByteWrapper[] byteWrappers = new ByteWrapper[pm.getPicList().size()];
			int i=0;
			StringBuilder sbImgs = new StringBuilder();
			//主图排第一位
			int mainIndex = Integer.valueOf(pm.getMainPicNum())-1;
			Collections.swap(pm.getPicList(), 0, mainIndex);
			
			for(PicModel.PicList pic:pm.getPicList()){
				String url = pic.getUrl();
				String picKey = url;
				if(picKey.contains("?")) {
					picKey = picKey.substring(0, picKey.indexOf("?"));
				}
				picKey = picKey.substring(picKey.lastIndexOf("/")+1);
				
				if(url.contains("aliyuncs.com") && !url.contains("image/resize")) {
					OSSObject ossObject = uploadFileService.getOSSObject(picKey);
					if(ossObject!=null){
						byteWrappers[i] =  new ByteWrapper(picKey,ossObject.getObjectContent(),ContentType.create("image/jpeg"));
					}
				} else {
					try {
						URL urlImg  = new URL(url);
						URLConnection con = urlImg.openConnection();
						con.setConnectTimeout(10*1000);
						byteWrappers[i] =  new ByteWrapper(picKey, con.getInputStream(), ContentType.create("image/jpeg"));
					} catch (Exception e) {
						e.printStackTrace();
					} 
				}
				
				sbImgs.append(picKey.substring(0, picKey.lastIndexOf(".")));
				if(i<(pm.getPicList().size()-1)){
					sbImgs.append(",");
				}
				i++;
			}
			itemImages.setByteWrappers(byteWrappers);
			itemImages.setImageIds(sbImgs.toString());
			return itemImages;
		}
		return null;
	}

*/


}
